/** 
 * 选择/添加成员的弹框组件
 * 用途：
 * 1. 群列表中添加朋友进群
 * 2. 多人音视频中选择群成员开启音视频
 * 
 * @param {object} option 开启弹框的属性配置
 * @param {string} option.type 打开弹窗的类型，不同类型打开不同的模板: 'list-select'(默认值) / 'list'
 * @param {num} option.limit 成员上限限制, 可以不传, 默认0
 * @param {boolean} option.isCompleteList 回调数据是否是完整的数据，即：完整就是所有选中的（包含初始传进来的selectedlist） / 还是当前手动选中的!, 可以不传, 默认false
 * @param {Array} option.list 待选择的成员列表
 * @param {string} option.selectedlist 已选择的成员列表
 * @param {object} option.env 执行环境，如果有的话，回调时需要重新绑定环境
 * @param {object} option.yx 缓存yx实例
 * @param {fn} option.cbConfirm 确认回调
 * @param {fn} option.cbCancel 取消回调
 */

YX.fn.dialog = {
    selectMemberList:[],//选中默认人员列表

    departOpers:[],//所有人员列表

    selectItemList:[],//选中人员label标签

    clickObj:{},//存储点击对象

    open: function (option) {
        this.limit = option.limit || 0;
        this.isCompleteList = option.isCompleteList || false;
        this.cbConfirm = option.cbConfirm || function () { };
        this.cbCancel = option.cbCancel || function () { };

        var $dialog = this.$dialog = $('#dialogTeamContainer'), that = this;

        this.type = option.type || 'list-select';
        that.yx = option.yx;
        that.env = option.env || that;
        that.selectedlist = {};
        that.load(option.list, option.selectedlist);
        that.selectedNum = 0;

        this.isOpen = true;

        // 事件绑定一次就行了
        if (that.isInited) return;

        $dialog.on('click', '.user-list li', function (e) {
            that.selectUser.call(that, e);
        });
        $dialog.on('click', '.j-close', function (e) {
            e.preventDefault();
            that.cbCancel.call(that.env);
            that.close();
        })
        $dialog.on('click', '.j-confirm', function (e) {
            e.preventDefault();
            if ($(this).hasClass('disabled')) return;
            that.close();
            if (!that.isCompleteList) {
                return that.cbConfirm.call(that.env, that.selectedlist);
            }
            var tmpList = {};
            $dialog.find('#addUserList li.selected').each(function (index, item) {
                item = $(item).data('account');
                tmpList[item] = item;
            });
            return that.cbConfirm.call(that.env, tmpList);
        });

        that.isInited = true;

    },
    /** dom渲染流程 */
    load: function (list, selectedlist) {
        var that = this;
        var dialog = that.$dialog;
        var fname = that.fname = that.type === 'list-select' ? 'teamMember' : 'speakBan';

        dialog.load('./' + fname + '.html', function () {
            if ($("#devices")) {
                $("#devices").addClass('hide')
            }
            dialog.removeClass('hide')
            that.yx.$mask.removeClass('hide')
            var $addIcon = $('#userList .first'),
                $addUserUl = $('#addUserList ul'),
                tmpHtml = '',
                members = []

            // 所有成员
            for (var i = 0, l = list.length; i < l; ++i) {

                var tmp = list[i];

                /** 奇怪的数据略过 */
                if (tmp.constructor !== Object) continue;
                /** 自己略过 */
                if (tmp.account === that.yx.accid) continue;

                var tmpUser = that.yx.cache.getUserById(tmp.account);
                tmp.avatar = tmpUser.avatar;
                tmp.name = tmp.nickInTeam;
                // tmp.nick = getNick(tmp.account);
                // tmp.nick = tmp.nick === tmp.account ? "" : tmp.nick;
                tmpHtml += appUI['build' + fname + 'UI'](tmp);
            }
            $addUserUl.html(tmpHtml);

            /** 禁言UI，放开按钮 */
            if (fname === 'speakBan') {
                dialog.find('.j-confirm').removeClass('disabled')
            }

            if (selectedlist) {
                that.loadSelected(selectedlist);
            }
        });
    },
    /**
     *  已选中的进行加载
     * 
     * @param {any} members object或者array都可以
     */
    loadSelected: function (members) {
        var fname = this.fname;

        if (!members) return;

        /** 对象转数组 */
        if (members.constructor === Object) {
            var arr = [];
            for (var i in members) {
                arr.push({
                    account: i
                });
            }
            members = arr;
        }

        /** 如果禁言，UI处理不一样 */
        if (fname === 'speakBan' && members.length > 0) {
            var $dialog = this.$dialog;
            for (var i = 0; i < members.length; i++) {
                var account = members[i].account
                $dialog.find('[data-account="' + account + '"]').addClass('selected')
                $dialog.find('[data-account="' + account + '"] i').addClass('cur')
            }
            // enable和disable按钮
            return;
        }

        /** 已选的ui */
        $('#addedUserNum').text(this.limit ? 0 + "/8" : 0)

        var $addUserUl = $('#addUserList ul');
        for (var i = 0; i < members.length; i++) {
            var account = members[i].account
            $addUserUl.find('[data-account="' + account + '"] i').addClass('cur2')
        }
    },
    /** 成员选择事件 */
    selectUser: function (e) {
        var that = this;
        // that.selectedNum = that.selectedNum || 0;
        var $this = $(e.target).closest('li'),
            $checkIcon = $this.find('i'),
            $addedUserNum = $('#addedUserNum'),
            $addedUserListUl = $('#addedUserList ul'),
            account = $this.data('account'),
            name = $this.data('nick'),
            icon = $this.data('icon'),
            addedNum = that.selectedNum
        // 不能被选择的人不响应事件
        if (!$checkIcon.hasClass('cur2')) {

            var str = '<li data-account="' + account + '" data-account="' + name + '" data-icon="' + icon + '"><img src="' + getAvatar(icon) + '" width="56" height="56"/><p class="name">' + name + '</p></li>'
            if (!$checkIcon.hasClass('cur')) {

                // 人数上限
                if (that.limit && addedNum >= that.limit) {
                    that.yx.myNetcall.showTip('人数已达上限', 2000);
                    return;
                }

                that.selectedlist[account] = name
                $addedUserListUl.append(str)
                addedNum++
            } else {
                delete that.selectedlist[account]
                $addedUserListUl.find('[data-account=' + account + ']').remove()
                addedNum--
            }

            $checkIcon.toggleClass('cur')
            $this.toggleClass('selected')
            $addedUserNum.text(that.limit ? addedNum + "/8" : addedNum)
            that.selectedNum = addedNum

            if (that.fname === 'speakBan') return;
            // enable和disable按钮
            that.$dialog.find('.j-confirm').toggleClass('disabled', addedNum <= 0)
        }

    },
    /** 关闭弹框 */
    close: function () {
        this.isOpen = false;
        this.$dialog && this.$dialog.addClass('hide')
        this.yx && this.yx.$mask && this.yx.$mask.addClass('hide')
    },
    //自定义选择成员方法
    openMember: function(selectMemberList,departOpers,teamId,that){
        console.log('treeData----------', departOpers);
        // console.log("this======",this)
        this.selectMemberList = selectMemberList;//选中人员列表
        this.departOpers = departOpers;//所有人员列表
        this.selectItemList = [];//选中人标签

        //first 将去组中已存在人员作为默认选中不可点击
        if(selectMemberList.length > 0){
            for(var i=0;i<selectMemberList.length;i++){
                var account = selectMemberList[i].account;
                for(var j=0;j<departOpers.length;j++){
                    if(account == departOpers[j].accId){
                        departOpers[j].checkArr[0].isChecked = '2';
                    }
                }
            }
        }

        var This=this;
        var OperTree;
        var Layer=layer.open({
        title:'邀请新成员入群',
        type: 1,
        // offset: '150px',
        content: '<div class="showTreeContent">'+
                    '<ul id="treeOperCon" data-id="0" class="dtree"></ul>'+
                    '<div class="treeRightInfo">'+
                        '<input type="text" placeholder="搜索" id="searchTreeMemberList" />'+
                        '<div class="searchBq" id="searchMemberLabel">'+
                            // '<span>刘福星<img src="images/closeItem.png"/></span><span>张盼<img src="images/closeItem.png"/></span><span>刘小米<img src="images/closeItem.png"/></span>'+
                        '</div>'+
                        '<div class="searchMemberList" id="searchMemberList">'+
                            // '<div class="searchTip">你可能想找的</div>'+
                            // '<ul>'+
                            //     '<li>'+
                            //         '<i class="dtree-icon-fuxuankuangxuanzhong dtree-layui-choose"></i>'+
                            //         '<img src="images/black.png" class="defaultTx"/>'+
                            //         '<div class="nameDet">'+
                            //             '<p class="xm">刘小米</p>'+
                            //             '<p class="bm">执行事业部</p>'+
                            //         '</div>'+
                            //     '</li>'+
                            //     '<li>'+
                            //         '<i class="dtree-icon-fuxuankuang"></i>'+
                            //         '<img src="images/black.png" class="defaultTx"/>'+
                            //         '<div class="nameDet">'+
                            //             '<p class="xm">刘小米</p>'+
                            //             '<p class="bm">执行事业部</p>'+
                            //         '</div>'+
                            //     '</li>'+
                            //     '<li>'+
                            //         '<i class="dtree-icon-fuxuankuangxuanzhong dtree-layui-choose"></i>'+
                            //         '<img src="images/black.png" class="defaultTx"/>'+
                            //         '<div class="nameDet">'+
                            //             '<p class="xm">刘小米</p>'+
                            //             '<p class="bm">执行事业部</p>'+
                            //         '</div>'+
                            //     '</li>'+
                            //     '<li>'+
                            //         '<i class="dtree-icon-fuxuankuang"></i>'+
                            //         '<img src="images/black.png" class="defaultTx"/>'+
                            //         '<div class="nameDet">'+
                            //             '<p class="xm">刘小米</p>'+
                            //             '<p class="bm">执行事业部</p>'+
                            //         '</div>'+
                            //     '</li>'+
                            // '</ul>'+
                        '</div>'+
                    '</div>'+
                    '</div>',
        btn:['确定','取消'],
        yes:function () {
            console.log("点击确定=",OperTree.getCheckbarNodesParam())
            // layer.close(Layer);
            // OperTree.reload({
            //     data: departOpers,
            // })
            if(This.selectItemList.length>0){
                var accounts = [];
                This.selectItemList.forEach(function(e){
                    accounts.push(e.accId)
                });
                if (teamId) {
                    console.log("accounts==",accounts)
                	that.mysdk.addTeamMembers({
                		teamId: teamId,
                		accounts: accounts,
                		ps: '',
                		done: function (error, params) {
                			if (error) { layer.msg("添加成员失败",{icon:2}) }
                		}
                    })
                    layer.close(Layer)
                    var members = that.cache.getTeamMembers(teamId).members.length + accounts.length;
                    that.$memberNum.text("( "+members+" )");

                	that.$teamInfoContainer.addClass('hide')
                }
            }
        },
        btn2:function () {
            layer.close(Layer)
        },
        success:function () {
            $(".layui-layer").css({"width":"auto"});
            OperTree = layui.dtree.render({
                elem: "#treeOperCon",
                dataFormat:'list',
                data: departOpers,
                type: "all",
                initLevel: 0,
                dot: false,  // 隐藏小圆点
                icon: "-1" , // 显示非最后一级节点图标，隐藏最后一级节点图标
                skin: "layui",
                checkbar:true,//复选框模式
                checkbarType:'self',
                checkbarData:'choose',
                checkbarFun :{
                    chooseBefore: function($i, node) { //复选框点击前的回调。
                        // console.log("复选框点击前i=",$i)
                        // console.log("复选框点击前node=",node)
                        if(node.ischecked == '2'){
                            return false
                        }
                        //此处需要清空右边筛选列表和搜索框的值
                        // This.clickObj={}
                        // if($("#searchMemberList")){
                        //     $("#searchMemberList").html("")
                        // }
                        // if($('#searchTreeMemberList')){
                        //     $('#searchTreeMemberList').val("")
                        // }

                        //获取相应的列表值
                        var labelItem = This.getAccIdAndName(node.nodeId);
                        var checked = node.ischecked;
                        var selectItemList = This.selectItemList;
                        if(checked == '0'){//即将选中 要添加列表
                            selectItemList.push(labelItem);
                            This.showSelectedLabel();
                        }else if(checked == '1'){//即将取消 要删除列表
                            var flagIndex = "";
                            for(var i=0;i<selectItemList.length;i++){
                                if(selectItemList[i].accId == labelItem.accId){
                                    flagIndex = i;
                                    break;
                                }
                            }
                            selectItemList.splice(flagIndex,1);
                            This.showSelectedLabel();
                        }
                        This.searchTreeMemberList();

                        return true;
                    },
                    chooseDone: function(checkbarNodesParam) { //复选框点击事件完毕后，返回该树关于复选框操作的全部信息。
                        // console.log("点击复选框之后=",checkbarNodesParam)
                    return ;
                    }
                }
            });
            // OperTree.setDisabledNodes("48");
            // layui.dtree.on("node('treeOperCon')" ,function(obj){
            //   console.log("1=",obj)
            //   if(JSON.parse(obj.param.basicData).isDept){
            //     console.log("2")
            //     OperTree.clickSpread(obj.dom)
            //   }else {
            //     console.log("3")
            //     if(obj.param.ischecked){
            //       console.log("4")
            //       // OperTree.checkStatus(obj.dom).check();
            //     }else {
            //       console.log("5")
            //       // OperTree.checkStatus(obj.dom).noCheck();
            //     }
            //   }
            //   //layer.msg(JSON.stringify(obj.param));
            // });

            var searchTreeMemberList = $('#searchTreeMemberList')
            searchTreeMemberList.bind("input propertychange",This.searchTreeMemberList.bind(This))
            searchTreeMemberList.blur(This.searchTreeMemberBlur.bind(This))
            searchTreeMemberList.focus(This.searchTreeMemberFocus.bind(This))
            $("#searchMemberList").delegate('.memberUl .memberLi','click',This.membersUlLiClick.bind(This))
            $("#searchMemberLabel").delegate('.spanLabel','click',This.searchMemberLabelClick.bind(This))

        }
        });
    },

    //绑定获取input输入框事件
    searchTreeMemberList:function(){
        this.clickObj={}
        $("#searchMemberList").html("");
        var $input = $('#searchTreeMemberList'),
        name = $input.val().trim(),
        that = this;
        searchList = new Array();
    //    console.log("$input====",name) 
       if(!name){
           return;
       }
        //根据name筛选人员列表
        // console.log("selectMemberList=",that.selectMemberList)
        // console.log("departOpers=",that.departOpers)
        // dtree-icon-fuxuankuangxuanzhong选中
        var departOpers = that.departOpers;
        var tmp = '<div class="searchTip">你可能想找的</div><ul class="memberUl">',
            flag = false,
            html = '';
        for(var i=0;i<departOpers.length;i++){
            if(departOpers[i].title.indexOf(name) != -1 && departOpers[i].accId){
                flag = true;
                var avatarImg = departOpers[i].avatar?departOpers[i].avatar:"images/black.png";
                if(that.judgeMemberByaccId(departOpers[i].accId)){
                    tmp += [
                        '<li class="memberLi" data-accId='+departOpers[i].accId+' data-name='+departOpers[i].title+' data-id='+departOpers[i].id+'>',
                            '<i class="dtree-icon-fuxuankuang-banxuan dtree-layui-choose"></i>',
                            '<img src='+avatarImg+' class="defaultTx"/>',
                            '<div class="nameDet">',
                                '<p class="xm">'+departOpers[i].title+'</p>',
                                '<p class="bm">'+departOpers[i].deptName+'</p>',
                            '</div>',
                        '</li>'
                    ].join("");
                }else if(that.judgeOthMemberByaccId(departOpers[i].accId,that.selectItemList)){
                    tmp += [
                        '<li class="memberLi" data-accId='+departOpers[i].accId+' data-name='+departOpers[i].title+' data-id='+departOpers[i].id+'>',
                            '<i class="dtree-icon-fuxuankuangxuanzhong dtree-layui-choose"></i>',
                            '<img src='+avatarImg+' class="defaultTx"/>',
                            '<div class="nameDet">',
                                '<p class="xm">'+departOpers[i].title+'</p>',
                                '<p class="bm">'+departOpers[i].deptName+'</p>',
                            '</div>',
                        '</li>'
                    ].join("");
                }else{
                    tmp +=[
                        '<li class="memberLi" data-accId='+departOpers[i].accId+' data-name='+departOpers[i].title+' data-id='+departOpers[i].id+'>',
                            '<i class="dtree-icon-fuxuankuang"></i>',
                            '<img src='+avatarImg+' class="defaultTx"/>',
                            '<div class="nameDet">',
                                '<p class="xm">'+departOpers[i].title+'</p>',
                                '<p class="bm">'+departOpers[i].deptName+'</p>',
                            '</div>',
                        '</li>'
                    ].join("");
                }
            }
        }
        tmp += '</ul>';
        if(!flag){
            html = '<div class="searchTip slt">未找到响应列表</div>'
        }else{
            html = tmp;
        }
        //插入Dom节点中
        $("#searchMemberList").html(html);
    },

    //获取聚焦事件
    searchTreeMemberBlur:function(){
        console.log("blur")
    },

    //获取失焦案件
    searchTreeMemberFocus:function(){
        console.log("focus")
        
    },

    //监听点击列表事件
    membersUlLiClick: function(e){
        //存储对象
        var account = e.currentTarget.getAttribute("data-accid");
        // var name = e.currentTarget.getAttribute("data-name");
        this.clickObj[account] = e;
        this.checkMembersUlLiClick(e);
    },

    //处理列表点击事件
    checkMembersUlLiClick: function(e){
        var account = e.currentTarget.getAttribute("data-accid");
        var name = e.currentTarget.getAttribute("data-name");
        var id = e.currentTarget.getAttribute("data-id")
        if(e.currentTarget.firstChild.classList.contains('dtree-icon-fuxuankuang-banxuan')){
            return;
        }
        // if(e.currentTarget.firstChild.classList.contains('dtree-icon-fuxuankuangxuanzhong')){
        //     //去除选中
        //     e.currentTarget.firstChild.classList.remove("dtree-icon-fuxuankuangxuanzhong");
        //     e.currentTarget.firstChild.classList.remove("dtree-layui-choose");
        //     e.currentTarget.firstChild.classList.add("dtree-icon-fuxuankuang");
        //     var selectItemList = this.selectItemList;
        //     var flag = false,flagIndex = "";
        //     for(var i=0;i<selectItemList.length;i++){
        //         if(selectItemList[i].accId == account){
        //             flag = true;
        //             flagIndex = i;
        //             break;
        //         }
        //     }
        //     //从左边树形中删除选中项
        //     $("#treeOperCon.dtree .dtree-nav-checkbox-div i[data-id="+id+"]").click();
           
        // }else{
        //     //添加选中
        //     e.currentTarget.firstChild.classList.remove("dtree-icon-fuxuankuang");
        //     e.currentTarget.firstChild.classList.add("dtree-icon-fuxuankuangxuanzhong");
        //     e.currentTarget.firstChild.classList.add("dtree-layui-choose"); 
        //     //从左边树形中添加选项
        //     $("#treeOperCon.dtree .dtree-nav-checkbox-div i[data-id="+id+"]").click();
        // }
        $("#treeOperCon.dtree .dtree-nav-checkbox-div i[data-id="+id+"]").click();
    },

    //监听点击label事件
    searchMemberLabelClick: function(e){
        var account = e.currentTarget.getAttribute("data-accid");
        var id = e.currentTarget.getAttribute("data-id");
        var flag = false,flagIndex = "";
        var selectItemList = this.selectItemList;
        var eObj = this.clickObj[account];
        if(eObj){
            this.checkMembersUlLiClick(eObj);
        }else{
            //刷新左边树形列表
            $("#treeOperCon.dtree .dtree-nav-checkbox-div i[data-id="+id+"]").click();
        } 
    },


    //显示选中标签
    showSelectedLabel: function(){
        $("#searchMemberLabel").html("");
        var selectItemList = this.selectItemList;
        var temp = "",
            flag = false,
            html = '';
        if(selectItemList && selectItemList.length > 0){
            for(var i=0;i<selectItemList.length;i++){
                flag = true;
                temp +='<span class="spanLabel" data-accId='+ selectItemList[i].accId + ' data-id='+ selectItemList[i].id +'>'+selectItemList[i].name+'<img src="images/closeItem.png"/></span>';
            }
            html = temp;
            if(!flag){
                $("#searchMemberLabel").html(html);
            }else{
                $("#searchMemberLabel").html(html);
            }
        }else{
            $("#searchMemberLabel").html(html);
        }
    },

    //根据accId判断某一成员是否在群组列表中
    judgeMemberByaccId:function(accId){
        var selectMemberList = this.selectMemberList;
        var flag = false;
        for(var i=0;i<selectMemberList.length;i++){
            if(selectMemberList[i].account == accId) {
                flag = true;
                break;
            }
        }
        return flag;
    },

    //根据accId判断某一成员是否在群组列表中
    judgeOthMemberByaccId:function(accId,list){
        var flag = false;
        for(var i=0;i<list.length;i++){
            if(list[i].accId == accId) {
                flag = true;
                break;
            }
        }
        return flag;
    },

    //根据nodeId获取accId和name
    getAccIdAndName: function(nodeId){
        var departOpers = this.departOpers;
        var data = {};
        for(var i=0;i<departOpers.length;i++){
            if(departOpers[i].id == nodeId){
                data.accId =  departOpers[i].accId;
                data.name = departOpers[i].title;
                data.id = departOpers[i].id
                break;
            }
        }
        return data;
    }
}